// var  urlSaveListDataIndex = "__CONTROLLER__/saveListDataIndex"
// const CONTROLLER = "__CONTROLLER__"

$(function() {
  /**
   * * 对Date的扩展，将 Date 转化为指定格式的String
   * * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
   * * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
   * * 例子：
   * * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
   * * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
   */
  Date.prototype.Format = function(fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : (
        "00" + o[k]).substr(("" + o[k]).length));
    }
    return fmt;
  };

  var time = new Date();
  var nowTime = time.Format('yyyy-MM-dd hh:mm');
  var nowYear = time.getFullYear();
  var nowMonth = time.getMonth();
  var choosableMonths = [];
  var minTime = time.Format('yyyy-MM-dd');
  for (var i = nowMonth; i <= 12; i++) {
    choosableMonths.push(i);
  }

  $("#datetime-picker").val(nowTime);
  $("#datetime-picker").datetimePicker({
    title: '截止日期',
    // 截止时间只能选择未来的时间
    min: minTime
  // years: [nowYear],
  // monthes: choosableMonths
  });

  // 投票可选项数目，默认是1
  var choice = 1

  // 添加题目
  $('#add-topic').click(function() {
    var topicTmp = `<div class="topic-wrapper">
          <div class="weui-cell weui-cell_access flex-justify-space-between">
            <div class="weui-cell___bd">
              <input class="weui-input select-item" type="text" placeholder="投票标题(必填)">
            </div>
            <!-- <div class="weui-cell__ft checkbox-box">
              <input type="text" class="checkbox-s" placeholder="1" />
            </div> --!>
          </div>
          <div class="select-group-item">
            <div class="weui-cell">
              <div class="weui-cell__hd"></div>
              <div class="weui-cell__bd">
                <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"></div>
              <div class="weui-cell__bd">
                <i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">
              </div>
            </div>
          </div>
          <a href="javascript:void(0);" class="weui-cell weui-cell_link">
            <div class="weui-cell__bd add-select-item">
              <i class="weui-icon-addition"></i>
              <p class="p_add-select-item">添加选项</p>
            </div>
            <div class="weui-cell__bd fr">
              <p class="msg-set">可选项数</p>
              <span class="icon icon-btn-substract">
                <i class="weui-icon-reduce"></i>
              </span>
              <input class="choice-num" type="number" name="" value="1" readonly>
              <span class="icon icon-btn-plus">
                <i class="weui-icon-addition"></i>
              </span>
            </div>
          </a>
          <div class="weui-cells__title delete-topic"><span class="close">+</span>删除本题</div>
        </div>`;

    $('.vote-box').append(topicTmp);

    $($(this).parent().prev().last().find('.checkbox-box')).trigger('click');
  });

  $('.vote-box').on('click', '.delete-topic', function(evt) {
    if (evt.currentTarget.parentNode && evt.currentTarget.parentNode.parentNode.children.length > 1) {
      console.log(evt.currentTarget.parentNode.parentNode.children.length);
      $(evt.currentTarget.parentNode).remove();
    }
  });

  var itemSelectArray;
  // 添加选项
  $('.vote-box').on('click', '.add-select-item', function(evt) {
    var selectTmp = '<div class="weui-cell">' + '<div class="weui-cell__hd">' + '</div>' +
      '<div class="weui-cell__bd">' +
      '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
      '</div>' + '</div>';
    var selectItem = $('.select-group-item .weui-cell').clone()[0] || selectTmp;
    $(selectItem).find('input').val('').attr('placeholder', '选项');
    $(evt.currentTarget.parentNode.parentNode.children[1]).append(selectItem);
    console.log($(this).parent().parent().find('.checkbox-box'));

    // fixed 自动触发一次点击事件，解决需要点击两次的bug
    $($(this).parent().parent().find('.checkbox-box')).trigger('click');
    console.log($(this).parent().parent().find('.checkbox-box'));
  });

  // 删除选项
  $('.vote-box').on('click', '.weui-icon-delete, .weui-icon-reduce', function(evt) {
    if (evt.currentTarget.parentNode.parentNode.parentNode.childElementCount > 2) {
      $(evt.currentTarget.parentNode.parentNode).remove();
    }
  });

  // 设置选项数，v2
  // 减少选项
  $('.vote-box').on('click', '.icon-btn-substract', function() {
    let $choiceNum = $(this).parents('.topic-wrapper').find('.choice-num').eq(0);
    if ($choiceNum.val() > 1) {
      $choiceNum.val(parseInt($choiceNum.val()) - 1);
    }
  })
  // 增加选项
  // TODO bug 部分手机浏览器无法增加
  $('.vote-box').on('click', '.icon-btn-plus', function() {
    // 获取选项数
    var selectGroupItem = $(this).parents('.topic-wrapper').children('.select-group-item');
    var itemNum = selectGroupItem.find('.select-item').length;
    itemSelectArray = Array.from({
      length: itemNum
    }).map(function(v, k) {
      return k + 1;
    });
    var maxItemNum = Math.max.apply(null, itemSelectArray);

    var $choiceNum = $(this).parents('.topic-wrapper').find('.choice-num').eq(0);
    console.log('TCL: $choiceNum', $choiceNum);

    var currentChoiceNum = $choiceNum.val()
    if (currentChoiceNum < maxItemNum) {
      $choiceNum.val(parseInt(currentChoiceNum) + 1);
    }
  })

  $('#submit').click(function() {
    var postData = [];
    var selectItem = $('.select-item');
    // [].map.call($('.select-item'), function (i) {
    //   console.log(i)
    // })

    $.map($('.vote-box .topic-wrapper'), function(topic, topicIndex) {
      // console.log(topic)
      var tmp = [];
      var itemData = [];
      $.map($(topic).find('.select-item'), function(item, itemIndex) {
        // console.log(itemIndex);
        var a = $($(item).find('.select-item')[itemIndex]);
        // console.log(a.val());
        itemData.push({
          "id": itemIndex,
          "name": $(item).val(),
          "value": itemIndex
        });
      });
      postData.push({
        "id": topicIndex,
        "name": $(topic).find('input').eq(0).val(),
        "value": topicIndex,
        "data": itemData,
        "choice": parseInt($(topic).find('.checkbox-s').val()) || choice
      });
      $('#datetime-picker').val();
    });

    var data = {
      "expiration": $('#datetime-picker').val(),
      "isAnonymous": $('#isAnonymous').is(':checked'),
      "vote": postData
    };

    console.log(data);
    $.ajax({
      type: "POST",
      url: CONTROLLER + "/saveListDataIndex",
      data: data,
      dataType: "json",
      success: function success(response) {
        console.log(response);
        if (response.errcode == 0) {
          console.log(data);
          $.alert({
            title: '',
            text: response.msg,
            onOK: function onOK() {
              location.href = CONTROLLER + '/poll/list_id/' + response.data;
            }
          });
        } else {
          $.alert(response.msg);
        }
      }
    });
  });

  /** 
   * * 控制单选多选
   */
  $('.vote-box').on('click', '.checkbox-box', function(evt) {
    var $this = $(this);
    // 获取选项数
    var selectGroupItem = $(this).parents('.topic-wrapper').children('.select-group-item');
    var itemNum = selectGroupItem.find('.select-item').length;
    itemSelectArray = Array.from({
      length: itemNum
    }).map(function(v, k) {
      return k + 1;
    });

    $($(this).children()).picker({
      title: '设置可选数',
      cols: [{
        textAlign: 'center',
        values: itemSelectArray ? itemSelectArray : [1, 2]
      }],
      defaultValue: [1],
      onClose: function onClose(picker) {
        console.log($($this).children().val());
      }
    });

    /**
     * * ref https://github.com/lihongxun945/jquery-weui/issues/341
     * ! fixed 
     */
    if ($($(this).children()).data('picker').cols[0]) {
      $($(this).children()).data('picker').cols[0].values = itemSelectArray ? itemSelectArray : [1, 2];
    }
  });

  // 加载完成自动触发一次
  $('.checkbox-box').trigger('click');

  // 获取微信分享jssdk
  $.ajax({
    type: "POST",
    url: urlList.getAppJssdkInfo,
    // url: 'https://herb.yicanfan123.com/mobile/api_get_signpackage.php',
    data: {
      url: window.location.href.split('#')[0] || postData.locationUrl
    },
    dataType: "json",
    success: function(response) {
      console.log(response)
      if (response.data) {
        let jssdk = response.data
        console.log(jssdk)
        wx.config({
          debug: false,
          appId: jssdk.appId,
          timestamp: jssdk.timestamp,
          nonceStr: jssdk.nonceStr,
          signature: jssdk.signature,
          jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            'chooseImage',
            'uploadImage',
            'onMenuShareTimeline',
            'hideOptionMenu',
            'showMenuItems',
            'onMenuShareAppMessage'
          ]
        });
        wx.ready(function() {
          wx.onMenuShareAppMessage({
            title: "", // 分享标题
            desc: "", // 分享描述
            link: "", // 分享链接
            imgUrl: '', // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function success() {
              $.toast('分享成功');
            },
            cancel: function cancel() {}
          });
          wx.onMenuShareTimeline({
            title: "", // 分享标题
            desc: "", // 分享描述
            link: "", // 分享链接
            imgUrl: '',
            success: function success() {
              $.toast('分享成功');
            },
            cancel: function cancel() {}
          });
        });
      }
    }
  })
});